package com.mars.pay.controller;

import com.mars.pay.common.Result;
import com.mars.pay.entity.Order;
import com.mars.pay.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单控制器
 *
 * @author Mars
 */
@Slf4j
@Controller
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    /**
     * 订单列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Order> orders = orderService.listAll();
        model.addAttribute("orders", orders);
        return "order-list";
    }

    /**
     * 创建订单
     */
    @PostMapping("/create")
    @ResponseBody
    public Result<Order> createOrder(@RequestParam String productName,
                                     @RequestParam(required = false) String productDesc,
                                     @RequestParam BigDecimal amount,
                                     @RequestParam(required = false, defaultValue = "10001") Long userId) {
        try {
            Order order = orderService.createOrder(productName, productDesc, amount, userId);
            return Result.success("创建订单成功", order);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/detail/{orderId}")
    @ResponseBody
    public Result<Order> getOrderDetail(@PathVariable Long orderId) {
        try {
            Order order = orderService.getByOrderId(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return Result.error("查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单号查询订单
     */
    @GetMapping("/query/{orderNo}")
    @ResponseBody
    public Result<Order> queryByOrderNo(@PathVariable String orderNo) {
        try {
            Order order = orderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return Result.error("查询订单失败：" + e.getMessage());
        }
    }
}

